<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/11/24
 * Time: 9:56
 */
namespace app\api\controller\directive\client;

use app\api\controller\BaseController;
use app\common\exception\CustomException;
use think\Db;
use think\Request;

class ClientController extends BaseController
{
    /**
     * @name 模块列表
     * @author wx
     * @date 2020/11/24 9:57
     */
    public function modules()
    {
        //接收参数
        $data = $this->filterInput();

        //根据hostkey查询数据
        $hostId = Db::name('host')->where('hostkey', $data['hostkey'])->value('id');
        if(!$hostId){
            throw new CustomException('客户端信息不存在', '202');
        }

        $info = Db::name('host_module_relation')->field('client, netfilter, disguise')->where('host_id', $hostId)->find();

        if(!$info){
            throw new CustomException('客户端未初始化', '202');
        }

        //构造数据
        $return = [];
        foreach ($info as $module => $status){
            $tmp['name'] = $module;
            $tmp['enable'] = $status ? true : false;

            $return[] = $tmp;
        }



        return $this->jsonOutPut($return);
    }

    /**
     * @name 卸载
     * @author wx
     * @date 2020/11/26 16:58
     */
    public function uninstall(Request $request)
    {
        //接收参数
        $params = $request->only(['hostkey', 'is_recovery']);

        $this->validate($params, 'Client.uninstall');


        if( isset($params['is_recovery']) ){

            $isRecovery = $params['is_recovery'] ? true : false;

        }else{
            $uninstallInfo = Db::name('host_uninstall')
                ->where('hostkey', $params['hostkey'])
                ->order('host_id', 'desc')
                ->find();

            if(!$uninstallInfo){
                throw new CustomException('未找到改客户端配置', '202');
            }

            if($uninstallInfo['status'] == 1){
                throw new CustomException('请勿重复访问', '202');
            }

            //修改回调状态
            Db::name('host_uninstall')
                ->where('id', $uninstallInfo['id'])
                ->update(['status' => 1, 'call_time' => time()]);

            $isRecovery = $uninstallInfo['is_recovery'];
        }

        $return = [
            'isRecovery' => $isRecovery ? true : false
        ];

        return $this->jsonOutPut($return);
    }
}